<template>
  <el-dialog
    v-model="visible"
    :title="$t('contacts.privacy.title')"
    width="500px"
    :before-close="handleClose"
  >
    <div class="privacy-content" v-loading="loading">
      <el-form :model="settingsForm" label-width="140px">
        <div class="settings-section">
          <h4 class="section-title">{{ $t('contacts.privacy.searchSettings') }}</h4>
          <p class="section-desc">{{ $t('contacts.privacy.searchSettingsDesc') }}</p>
          
          <el-form-item :label="$t('contacts.privacy.allowUsernameSearch')">
            <el-switch
              v-model="settingsForm.allowSearchByUsername"
              :active-text="$t('contacts.privacy.allow')"
              :inactive-text="$t('contacts.privacy.deny')"
            />
            <div class="setting-help">
              {{ $t('contacts.privacy.usernameSearchDesc') }}
            </div>
          </el-form-item>
          
          <el-form-item :label="$t('contacts.privacy.allowEmailSearch')">
            <el-switch
              v-model="settingsForm.allowSearchByEmail"
              :active-text="$t('contacts.privacy.allow')"
              :inactive-text="$t('contacts.privacy.deny')"
            />
            <div class="setting-help">
              {{ $t('contacts.privacy.emailSearchDesc') }}
            </div>
          </el-form-item>

          <el-form-item :label="$t('contacts.privacy.allowRealNameSearch')">
            <el-switch
              v-model="settingsForm.allowSearchByRealName"
              :active-text="$t('contacts.privacy.allow')"
              :inactive-text="$t('contacts.privacy.deny')"
            />
            <div class="setting-help">
              {{ $t('contacts.privacy.realNameSearchDesc') }}
            </div>
          </el-form-item>
        </div>

        <el-divider />

        <div class="settings-section">
          <h4 class="section-title">{{ $t('contacts.privacy.onlineStatus') }}</h4>
          <p class="section-desc">{{ $t('contacts.privacy.onlineStatusDesc') }}</p>

          <el-form-item :label="$t('contacts.privacy.showOnlineStatus')">
            <el-switch
              v-model="settingsForm.showOnlineStatus"
              :active-text="$t('contacts.privacy.show')"
              :inactive-text="$t('contacts.privacy.hide')"
            />
            <div class="setting-help">
              {{ $t('contacts.privacy.onlineStatusHelp') }}
            </div>
          </el-form-item>
        </div>

        <el-divider />

        <div class="settings-section">
          <h4 class="section-title">{{ $t('contacts.privacy.friendRequests') }}</h4>
          <p class="section-desc">{{ $t('contacts.privacy.friendRequestsDesc') }}</p>

          <el-form-item :label="$t('contacts.privacy.acceptFriendRequests')">
            <el-switch
              v-model="settingsForm.allowFriendRequests"
              :active-text="$t('contacts.privacy.accept')"
              :inactive-text="$t('contacts.privacy.reject')"
            />
            <div class="setting-help">
              {{ $t('contacts.privacy.friendRequestsHelp') }}
            </div>
          </el-form-item>

          <el-form-item :label="$t('contacts.privacy.autoAcceptTeamMembers')">
            <el-switch
              v-model="settingsForm.autoAcceptTeamMembers"
              :active-text="$t('contacts.privacy.autoAccept')"
              :inactive-text="$t('contacts.privacy.manualProcess')"
            />
            <div class="setting-help">
              {{ $t('contacts.privacy.autoAcceptTeamMembersHelp') }}
            </div>
          </el-form-item>
        </div>

        <el-divider />

        <div class="settings-section">
          <h4 class="section-title">{{ $t('contacts.privacy.securityTips') }}</h4>
          <el-alert
            :title="$t('contacts.privacy.privacyProtectionTips')"
            type="info"
            :closable="false"
            show-icon
          >
            <ul class="security-tips">
              <li>{{ $t('contacts.privacy.tip1') }}</li>
              <li>{{ $t('contacts.privacy.tip2') }}</li>
              <li>{{ $t('contacts.privacy.tip3') }}</li>
              <li>{{ $t('contacts.privacy.tip4') }}</li>
            </ul>
          </el-alert>
        </div>
      </el-form>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">{{ $t('common.cancel') }}</el-button>
        <el-button @click="resetToDefault">{{ $t('contacts.privacy.resetToDefault') }}</el-button>
        <el-button
          type="primary"
          @click="handleSave"
          :loading="saving"
        >
          {{ $t('contacts.privacy.saveSettings') }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useContactsStore } from '@/stores/contacts'

// Props & Emits
const props = defineProps<{
  modelValue: boolean
}>()

const emit = defineEmits<{
  'update:modelValue': [value: boolean]
  'updated': []
}>()

// 状态管理
const contactsStore = useContactsStore()

// 响应式数据
const loading = ref(false)
const saving = ref(false)

const settingsForm = reactive({
  allowSearchByUsername: true,
  allowSearchByEmail: false,
  allowSearchByRealName: false,
  showOnlineStatus: true,
  allowFriendRequests: true,
  autoAcceptTeamMembers: false
})

// 默认设置
const defaultSettings = {
  allowSearchByUsername: true,
  allowSearchByEmail: false,
  allowSearchByRealName: false,
  showOnlineStatus: true,
  allowFriendRequests: true,
  autoAcceptTeamMembers: false
}

// 计算属性
const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

// 监听对话框打开，加载设置
watch(visible, async (newVisible) => {
  if (newVisible) {
    await loadPrivacySettings()
  }
})

// 方法
const loadPrivacySettings = async () => {
  try {
    loading.value = true
    const settings = await contactsStore.getPrivacySettings()
    
    // 更新表单数据
    Object.assign(settingsForm, {
      allowSearchByUsername: settings.allowSearchByUsername,
      allowSearchByEmail: settings.allowSearchByEmail,
      allowSearchByRealName: settings.allowSearchByRealName,
      showOnlineStatus: settings.showOnlineStatus,
      allowFriendRequests: settings.allowFriendRequests,
      autoAcceptTeamMembers: settings.autoAcceptTeamMembers
    })
    
  } catch (error) {
    console.error('加载隐私设置失败:', error)
    ElMessage.error('加载隐私设置失败')
  } finally {
    loading.value = false
  }
}

const handleSave = async () => {
  try {
    saving.value = true
    
    await contactsStore.updatePrivacySettings(settingsForm)
    
    visible.value = false
    emit('updated')
    
  } catch (error) {
    console.error('保存隐私设置失败:', error)
  } finally {
    saving.value = false
  }
}

const resetToDefault = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要恢复到默认设置吗？这将覆盖您当前的所有隐私设置。',
      '恢复默认设置',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    Object.assign(settingsForm, defaultSettings)
    ElMessage.success('已恢复默认设置，请点击保存生效')
    
  } catch (error) {
    // 用户取消操作
  }
}

const handleClose = () => {
  visible.value = false
}
</script>

<style scoped>
.privacy-content {
  max-height: 600px;
  overflow-y: auto;
}

.settings-section {
  margin-bottom: 24px;
}

.section-title {
  margin: 0 0 8px 0;
  font-size: 16px;
  font-weight: 500;
  color: var(--el-text-color-primary);
}

.section-desc {
  margin: 0 0 16px 0;
  font-size: 14px;
  color: var(--el-text-color-regular);
  line-height: 1.5;
}

.setting-help {
  margin-top: 4px;
  font-size: 12px;
  color: var(--el-text-color-placeholder);
  line-height: 1.4;
}

.security-tips {
  margin: 8px 0 0 0;
  padding-left: 20px;
}

.security-tips li {
  margin-bottom: 4px;
  font-size: 14px;
  color: var(--el-text-color-regular);
  line-height: 1.4;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

:deep(.el-form-item) {
  margin-bottom: 20px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: var(--el-text-color-primary);
}

:deep(.el-switch) {
  --el-switch-on-color: var(--el-color-primary);
}

:deep(.el-divider) {
  margin: 24px 0;
}

:deep(.el-alert) {
  margin-top: 16px;
}

:deep(.el-alert .el-alert__content) {
  padding-right: 0;
}
</style>
